package com.ds.infra.mq.core.network;

import com.ds.infra.mq.core.protocol.Message;
import com.ds.infra.mq.core.protocol.MessageType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 作用：处理客户端的请求，并根据不同的消息类型调用相应的处理器。
 *
 * @author WeiShaoying
 */
@ChannelHandler.Sharable
@Slf4j
public class ServerHandler extends SimpleChannelInboundHandler<Message> {

    private final RequestProcessor requestProcessor;

    public ServerHandler(RequestProcessor requestProcessor) {
        this.requestProcessor = requestProcessor;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) {
        MessageType messageType = msg.getMessageType();
        try {
            Message response = switch (messageType) {
                case PRODUCE_REQUEST -> requestProcessor.handleProduceRequest(msg);
                case CONSUME_REQUEST -> requestProcessor.handleConsumeRequest(msg);
                case HEARTBEAT -> requestProcessor.handleHeartbeat(msg);
                default -> throw new IllegalStateException("Unexpected message type: " + messageType);
            };
            ctx.writeAndFlush(response);
        } catch (Exception e) {
            log.error("Process message error", e);
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Channel error", cause);
        ctx.close();
    }
}
